from ._base import BaseModel
from ..extends.flask_sqlalchemy import db
from flask import url_for


class Category(BaseModel):
    parent_id = db.Column(db.Integer, nullable=False, default=0, index=True, comment='父栏目')
    level = db.Column('level', db.String(30), nullable=False, default='0', comment='栏目等级')
    title = db.Column(db.String(30), nullable=False, index=True, comment='栏目名称')
    keyword = db.Column(db.String(30), nullable=False, default='', comment='栏目关键词')
    intro = db.Column(db.String(128), nullable=False, default='', comment='栏目简介')
    is_menu = db.Column(db.Boolean, nullable=False, default=True, comment='设置为菜单')
    menu_name = db.Column(db.String(30), nullable=False, index=True, comment='菜单名称')
    thumbnail = db.Column(db.String(200), nullable=False, default=True, comment='栏目封面')
    grade = db.Column(db.SmallInteger, nullable=False, default=0, comment='栏目等级')
    path = db.Column(db.String(50), nullable=False, index=True, comment='栏目路径')
    number = db.Column(db.SmallInteger, nullable=False, default=20, comment='显示数量')

    article = db.relationship(
        'Article',
        foreign_keys="Article.category_id",
        primaryjoin="Category.id == Article.category_id",
        order_by='Article.id.desc()',
        lazy='dynamic'
    )
    children = db.relationship(
        'Category',
        foreign_keys=parent_id,
        primaryjoin="Category.parent_id == Category.id"
    )
    parent = db.relationship(
        'Category',
        foreign_keys=parent_id,
        remote_side='Category.id',
        primaryjoin="Category.parent_id == Category.id",
    )

    @classmethod
    def create(cls, field):
        parent = cls.query.get(field.get('parent_id'))
        with db.auto_commit():
            this = cls()
            this.set_fields(field)
            if parent:
                this.path = '/'.join([parent.path, this.path])
                this.level = '{}-{}'.format(parent.level, parent.id)
            else:
                this.level = '0'
            db.session.add(this)
        return this

    def update(self, field):
        with db.auto_commit():
            self.set_fields(field)
            if self.parent:
                self.level = '{}-{}'.format(self.parent.level, self.parent.id)
            else:
                self.level = '0'
        return self

    @property
    def url(self):
        return url_for('home.category_select', path=self.path)

    @classmethod
    def html_tree(cls, pid=0):
        _all = cls.query.filter_by(parent_id=pid).all()
        tree = []
        cls._closure(_all, tree)
        return tree

    @classmethod
    def _closure(cls, result, tree):
        _total = len(result)
        _count = 0
        for item in result:
            _count = _count + 1
            if item.parent_id != 0:
                if _count == _total:
                    item.mark = '└─'
                else:
                    item.mark = '├─'
            else:
                item.mark = ''
            item.parent = item.parent
            tree.append(item)
            if item.children:
                cls._closure(item.children, tree)
